package threading.runnable;

import java.io.File;

import javax.swing.SwingUtilities;


import objects.data.WorkPacket;


import ssh.SSHUtils;
import utils.Utils;
import utils.ZipUtils;
import web.Hosts;
import gui.GUIUtils;
import gui.filetree.TreeUtils;
import gui.filetree.TreeNode;
import gui.main.MainPanelGUIView;


public class JobSubmitter implements Runnable{
	
	@Override
	public void run() {
		MainPanelGUIView mainPanel = GUIUtils.MainPanel;
		WorkPacket workPacket = WorkPacket.getInstance();
		if(workPacket == null) {
			return;
		}
		
		mainPanel.submitB.setEnabled(false);
		
		mainPanel.setMessageLbl("Zipping job files");
		workPacket.sourceDir = ZipUtils.zipAndName(workPacket.sourceDir,workPacket.jobname);

		
		mainPanel.setMessageLbl("Uploading job files to file server");
		if (SSHUtils.CmdTo("mkdir ~/" + workPacket.uniqueId) == null) {
			mainPanel.setMessageLbl("Error creating dir on SSH server");
			return;
		}
		if (!SSHUtils.ScpTo(workPacket.sourceDir, workPacket.uniqueId, new File(workPacket.sourceDir).getName() )) {
			
			mainPanel.setMessageLbl("Error uploading file to SSH server");
			return;
		}
		
		new File(workPacket.sourceDir).delete();
		
		TreeUtils.insertFromWorkPacket(workPacket);
		
		//TODO ADD IT TO JOB PANEL
		
		try {
			Hosts.ws.send(workPacket);
			Utils.userInfo.workPacketMap.put(workPacket.uniqueId, workPacket);
			mainPanel.setMessageLbl("Job submission was succesful");
			
		} catch (Exception e) {
			mainPanel.setMessageLbl("Job submission failed: "+e.getMessage());
			e.printStackTrace();
		}
		Utils.out("Done");
		mainPanel.submitB.setEnabled(true);
	}

}
